<template>
  <div>
    <div class="chat-container">
      <div class="sidebar">
        <div class="sidebar-header">
          <h3>交流记录</h3>
          <el-button type="primary" size="small" @click="createNewChat">新建会话</el-button>
        </div>
        <div class="chat-list">
          <div 
            v-for="(chat, index) in chatList" 
            :key="index" 
            :class="['chat-item', currentChatIndex === index ? 'active' : '']"
            @click="selectChat(index)">
            <span class="chat-title">{{chat.title}}</span>
            <span class="chat-date">{{chat.date}}</span>
          </div>
        </div>
      </div>
      
      <div class="chat-main">
        <div class="chat-header">
          <h3>{{currentChat.title}}</h3>
          <div class="participants">
            <el-tag 
              v-for="(participant, index) in currentChat.participants" 
              :key="index"
              type="info"
              size="small">{{participant}}</el-tag>
          </div>
        </div>
        
        <div class="message-container" ref="messageContainer">
          <div v-for="(message, index) in currentChat.messages" :key="index" :class="['message', message.type]">
            <div class="message-header">
              <span class="sender">{{message.sender}}</span>
              <span class="time">{{message.time}}</span>
            </div>
            <div class="message-content">
              <p>{{message.content}}</p>
              <div v-if="message.attachments && message.attachments.length" class="attachments">
                <div v-for="(file, fileIndex) in message.attachments" :key="fileIndex" class="attachment">
                  <i class="el-icon-document"></i>
                  <span>{{file.name}}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="message-input">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="输入消息..."
            v-model="newMessage"
            @keyup.ctrl.enter.native="sendMessage">
          </el-input>
          <div class="input-actions">
            <el-upload
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleUploadSuccess">
              <el-button size="small" type="text">
                <i class="el-icon-paperclip"></i> 附件
              </el-button>
            </el-upload>
            <el-button type="primary" @click="sendMessage">发送</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      chatList: [
        {
          id: 1,
          title: '预制菜原料采购交流',
          date: '2023-03-24',
          participants: ['管理员', '湖南农耕食品有限公司'],
          messages: [
            {
              type: 'received',
              sender: '湖南农耕食品有限公司',
              time: '10:15',
              content: '您好，我们这边最近有新鲜的韭菜上市，可以为您的预制菜提供原材料。',
              attachments: []
            },
            {
              type: 'sent',
              sender: '管理员',
              time: '10:20',
              content: '你好，请问价格怎么样？品质如何保证？',
              attachments: []
            },
            {
              type: 'received',
              sender: '湖南农耕食品有限公司',
              time: '10:30',
              content: '我们的韭菜采用有机种植方式，价格是8元/斤，可以提供产地证明和检测报告。',
              attachments: [
                { name: '检测报告.pdf', url: '#' }
              ]
            }
          ]
        },
        {
          id: 2,
          title: '速冻水饺质量问题反馈',
          date: '2023-03-23',
          participants: ['管理员', '消费者'],
          messages: [
            {
              type: 'received',
              sender: '消费者',
              time: '15:40',
              content: '你好，我购买的速冻水饺包装有破损，请问如何处理？',
              attachments: [
                { name: '包装照片.jpg', url: '#' }
              ]
            },
            {
              type: 'sent',
              sender: '管理员',
              time: '15:45',
              content: '您好，非常抱歉给您带来不便。请提供您的购买凭证和收货地址，我们会尽快为您更换新的产品。',
              attachments: []
            }
          ]
        }
      ],
      currentChatIndex: 0,
      newMessage: '',
      attachments: []
    }
  },
  
  computed: {
    currentChat() {
      return this.chatList[this.currentChatIndex] || {
        title: '新对话',
        participants: ['管理员'],
        messages: []
      }
    }
  },
  
  mounted() {
    this.scrollToBottom()
  },
  
  updated() {
    this.scrollToBottom()
  },
  
  methods: {
    selectChat(index) {
      this.currentChatIndex = index
    },
    
    createNewChat() {
      const newChat = {
        id: this.chatList.length + 1,
        title: '新建对话',
        date: this.formatDate(new Date()),
        participants: ['管理员'],
        messages: []
      }
      this.chatList.unshift(newChat)
      this.currentChatIndex = 0
      
      this.$prompt('请输入对话标题', '新建对话', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        newChat.title = value
      }).catch(() => {
        // 取消操作
      })
    },
    
    sendMessage() {
      if (!this.newMessage.trim() && this.attachments.length === 0) return
      
      const now = new Date()
      const message = {
        type: 'sent',
        sender: '管理员',
        time: `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`,
        content: this.newMessage,
        attachments: [...this.attachments]
      }
      
      this.currentChat.messages.push(message)
      this.newMessage = ''
      this.attachments = []
      
      // 模拟回复
      if (Math.random() > 0.5) {
        setTimeout(() => {
          const reply = {
            type: 'received',
            sender: this.currentChat.participants[1] || '系统',
            time: `${now.getHours()}:${(now.getMinutes() + 1).toString().padStart(2, '0')}`,
            content: '收到您的消息，我们将尽快处理。',
            attachments: []
          }
          this.currentChat.messages.push(reply)
        }, 1500)
      }
    },
    
    handleUploadSuccess(response, file) {
      this.attachments.push({
        name: file.name,
        url: URL.createObjectURL(file.raw)
      })
    },
    
    scrollToBottom() {
      this.$nextTick(() => {
        if (this.$refs.messageContainer) {
          this.$refs.messageContainer.scrollTop = this.$refs.messageContainer.scrollHeight
        }
      })
    },
    
    formatDate(date) {
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  height: calc(100vh - 230px);
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.sidebar {
  width: 250px;
  border-right: 1px solid #eaeaea;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eaeaea;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
}

.chat-list {
  flex: 1;
  overflow-y: auto;
}

.chat-item {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.chat-item:hover {
  background-color: #f5f7fa;
}

.chat-item.active {
  background-color: #ecf5ff;
}

.chat-title {
  display: block;
  font-weight: bold;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-date {
  font-size: 12px;
  color: #909399;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 15px;
  border-bottom: 1px solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header h3 {
  margin: 0;
  font-size: 16px;
}

.participants {
  display: flex;
  gap: 5px;
}

.message-container {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
}

.message {
  margin-bottom: 15px;
  max-width: 80%;
}

.message.sent {
  margin-left: auto;
}

.message.received {
  margin-right: auto;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.sender {
  font-weight: bold;
  font-size: 13px;
}

.time {
  font-size: 12px;
  color: #909399;
}

.message-content {
  padding: 10px 15px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.message.sent .message-content {
  background-color: #ecf5ff;
}

.message-content p {
  margin: 0;
  white-space: pre-wrap;
}

.attachments {
  margin-top: 10px;
  border-top: 1px solid #eaeaea;
  padding-top: 10px;
}

.attachment {
  display: flex;
  align-items: center;
  padding: 5px 0;
  font-size: 12px;
  color: #409eff;
  cursor: pointer;
}

.attachment i {
  margin-right: 5px;
}

.message-input {
  padding: 15px;
  border-top: 1px solid #eaeaea;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
</style> 